<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>租户详细信息</title>
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1" />
	
<link href="${mvcPath}/dacp-view/aijs/css/ai.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="${mvcPath}/dacp-lib/ztree/zTreeStyle.css" type="text/css">


<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
.fuelux .wizard {
	border-right: 0px;
	border-bottom: 1px solid #eee;
	box-shadow: 0 0px 0px;
	background-color: transparent;
	box-shadow: none;
	border-radius: 0px;
}

.wrapper {
	padding: 1px 15px 15px 15px;
}

.panel-body {
	padding: 2px 0px 5px 0px;
}
#tab5 thead th{
    background: #f8f8f8;
}
#tab5 .pageContainer{
	display: none;
}
#tab5 select,input{
	border: none !important;
	background-color: rgba(250, 250, 250, 0);
	padding: 0px;
}
#tab5 table tr{
	border: 1px solid #eee;
}
#team_flow_info table tr td{
	padding: 3px !important;
}
#team_flow_info table tr td select{
	height: 22px;
}
.ai-grid thead th {
    background: #36B0C8;
    color: #979FA5;
}
.form-control {
    display: block;
    width: 100%;
    height: 30px;
    padding: 6px 4px;
    line-height: 1.42857143;
    color: #555;
    background-image: none;
    border: 1px solid #ccc !important;
}
#teambaseinfo tr th:first-child{min-width:100px}
.ai-grid-container {
	height:380px !important;
}
.ai-table-container {
	height:380px !important;
}

</style>
<script type="text/javascript" src="${mvcPath}/dacp-lib/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/ztree/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/dacp-me-deploy/dacp-lib/underscore/underscore-min.js"></script>
<script src="${mvcPath}/dacp-lib/cryptojs/aes.js" type="text/javascript"></script>
<script src="${mvcPath}/crypto/crypto-context.js" type="text/javascript"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.grid.js"></script>
<script src="${mvcPath}/dacp-lib/underscore/underscore-min.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.treeview.js"> </script>
 <script src="${mvcPath}/dacp-res/catalog/common/js/ai.meta.widget.js"></script>
<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
 
.wrapper {
	padding: 1px 15px 15px 15px;
}
 
a.plan {
	font-size: 14px;
}

a.task {
	font-size: 13px;
}

.toolbar {
	margin-top: 10px;
	margin-bottom: 10px;
}

.toolbar .form-control {
	display: inline;
	padding: 1px 2px;
}

.toolbar button {
	margin-left: 10px;
}
.panel .table-striped > thead th {
    background-color: #36B0C8;
}
.form-horizontal .form-group {
    margin-left: 0px;
    margin-right: 0px;
}

.ztree .line {
	height: auto;
}
.ai-grid thead th {
    background: #f8f8f8;
}
.glyphicon-edit{
	display: none !important;
}
.empty{
	border-bottom: none;
	font-size: 14px;
	font-style: italic;
	padding: 20px;
	text-align: center;
	width: 100%;
}
</style>
<script>
TeamPerMission={
	 ruleTreeGrid:null,
	  treesql:"SELECT TEAM_CODE, RULE_CODE, PARENTCODE, RULETYPE, RULENAME, RULETEXT, DBNAME, TOPICNAME, REMARK FROM meta_team_permission where team_code='{team_code}'   order by rule_code",
	  config : {
				id : "metaTeamPerssionInfo",
				width : "800",
				renderTo : "metaTeamPerssionInfo",
				headerAlign : "left",
				headerHeight : "30",
				dataAlign : "left",
				indentation : "8",
				hoverRowBackground : "true",
				folderColumnIndex : "0",
				itemClick : this.itemClickEvent,
				//showcheck:true,
				columns : [ 
					
					{headerText : "名称", dataField : "RULENAME", headerAlign : "center", width : "220", dataAlign : "center",handler:this.ruleNameRender}, 
					{headerText : "操作", dataField : "ACT", headerAlign : "center", width : "150", dataAlign : "center" ,handler:this.actRender},
					{headerText : "规则编号", dataField : "RULE_CODE", headerAlign : "center", width : "220" }, 
					{headerText : "备注", dataField : "REMARK", headerAlign : "center", dataAlign : "center", width : "320"}
					//,{headerText : "规则描述", dataField : "REMARK", headerAlign : "center", width : "320", dataAlign : "center" }
				],
				keyfield : "RULE_CODE",
				pkeyfield : "PARENTCODE",
				titlefield : "RULENAME",
				iconfield : "",
				store:null,
				subtype : 'treegrid'
	  },
	 itemClickEvent:function(id, index, data) {
           //console.log( id + ", " + index + ", " 	+ TreeGrid.json2str(data));
			   // console.log(TeamPerMission.ruleTreeGrid.getSelectedItem());
	  },
	  ruleNameRender:function(row, col){
	    if(!row.PARENTCODE) return '<b>'+row.RULENAME+'<b> '
	    else return row.RULENAME ;
	  },
	  remarkRender:function(row, col){
	    if(row.REMARK && row.REMARK.length>40) return row.REMARK.substr(1,40)+'.... '
	    else return row.REMARK ;
	  },
	  actionItems:{
	  	  synatic:{title:'同步数据库',icon:'glyphicon glyphicon-refresh'},
	  	  pickdbTopic:{title:'选择主题',icon:'glyphicon glyphicon-zoom-in'},
	  	  add:{title:'增加',icon:'glyphicon glyphicon-plus'},
	  	  del:{title:'删除',icon:'glyphicon glyphicon-remove'},
	  	  edit:{title:'编辑',icon:'glyphicon glyphicon-pencil'},
	  	  addSoftware:{title:'增加',icon:'glyphicon glyphicon-plus'},
	  },
	 
	  deleteRule:function(){
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var teamcode = this.teamcode;
	  	var removeRowKeys = [];
	  	
	  	function delteNode(node){
	  		var nodeChilds = node.getChildren();
	  		if(nodeChilds.length > 0){
	  			for(var j=0;j<nodeChilds.length;j++){
		  			delteNode(nodeChilds[j]);
		  			var nodeRuleCode = nodeChilds[j].data.RULE_CODE;
		  		}
		  		removeRowKeys.push(teamcode+","+node.data.RULE_CODE);
	  		}else{
	  			var nodeRuleCode = node.data.RULE_CODE;
	  			removeRowKeys.push(teamcode+","+nodeRuleCode);
	  		}
	  	}
	  	
	  	var alertMsg = "确定删除?";
	  	if(curItem.getChildren().length > 0){
	  		alertMsg = "确定删除当前节点及其子节点?";
	  	}
	  	if(window.confirm(alertMsg)){
	  		delteNode(curItem);
	  		for(var k=0;k<removeRowKeys.length;k++){
		  		var r = this.config.store.getRecordByKey(removeRowKeys[k]);
		  		this.config.store.remove(r);
		  	}
	    	this.config.store.commit();
	    	this.init(this.options);
	    	//this.reset();
	    }
	  },
	  addRule:function(){
	  	 var ruleObj =null;
	  	var aftSave=function(fieldVals){
	  		var newRuelCode = ai.getNewCode(TeamPerMission.config.store,"RULE_CODE",curItem.data.RULE_CODE+"-");//store,fieldname,pre,tabname
	  	 
              	var ruleText = ai.toJSON(ruleObj);
              	var r=TeamPerMission.config.store.getNewRecord();
         		r.set('TEAM_CODE',TeamPerMission.teamcode);
         		r.set('RULE_CODE',newRuelCode);
         		r.set('PARENTCODE',curItem.data.RULE_CODE);
         		r.set('RULETYPE','rule');
         		r.set('RULENAME',ruleObj.RULENAME+"("+ruleObj.RIGTHLEVEL+")");
         		r.set('RULETEXT',ruleText);
         		r.set('REMARK',ruleText);
         		TeamPerMission.config.store.add(r);
         		TeamPerMission.config.store.commit();
         	    TeamPerMission.reset(TeamPerMission.options);
	  	};
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=this.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	
	  	var ruleText = r.get('RULETEXT')||"{}";
	  	ruleObj = jQuery.parseJSON(ruleText)||{};
	  	
	  	var useRigthRuleForm = ({
				id : 'form',
				items : [{ type : 'text', label : '规则名称', fieldName : 'RULENAME', width : 220},
							{ type : 'html', html : '<hr>', fieldName : 'TEAM_CODE', width : 220},
							{ type : 'pick-grid', label : '开发租户', fieldName : 'TEAM_CODE',storesql:"select TEAM_CODE VALUES1,TEAM_NAME VALUES2 from meta_team where TEAM_CODE<>'"+this.teamcode+"'", width : 220},
							{ type : 'checkbox', label : '数据库', fieldName : 'DBNAME',storesql:"select dbname,CNNAME from metadbcfg where dbname<>'METADB'", width : 420  },
							{ type : 'text', label : '主题包含', fieldName : 'TOPICCODE', width : 220  } ,
							{ type : 'text', label : '表名包含', fieldName : 'OBJNAME', width : 220  } ,
							{ type : 'checkbox', label : '权限级别', fieldName : 'RIGTHLEVEL',storesql:'一级敏感,二级敏感,普通', width : 220  },
							{ type : 'html', html : '<hr>', fieldName : 'TEAM_CODE', width : 220},
							{ type : 'combox', label : '<b>授权类型</b>', fieldName : 'RIGTHLEVEL', storesql:'免授权,申请授权,不允许申请',width : 220  },
							],
				fieldChange:function(fieldName, newVal){ 
					  console.log(fieldName,newVal);
					  ruleObj[fieldName]=newVal;
				}
			});
			for(var i=0;i<useRigthRuleForm.items.length;i++){
				var item = useRigthRuleForm.items[i];
				if(ruleObj[item.fieldName]) item.value=ruleObj[item.fieldName];
			};
	       ai.showDialogForm(useRigthRuleForm,null,aftSave);
	  },
	  /* editRule:function(){
	  	var ruleObj =null;
	  	var aftSave=function(fieldVals){
	  		 console.log(_global_from.fields);
	  		 
              	 var ruleText = ai.toJSON(ruleObj);
         		TeamPerMission.config.store.curRecord.set('RULETEXT',ruleText);
         		TeamPerMission.config.store.curRecord.set('RULENAME',ruleObj.RULENAME+"("+ruleObj.RIGTHLEVEL+")");
         		TeamPerMission.config.store.commit();
         		TeamPerMission.reset(TeamPerMission.options);
	  	};
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=TeamPerMission.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	var _data = r.get('RULETEXT');
	  	var ruleText = _data||"{}";
	  	ruleObj = jQuery.parseJSON(ruleText)||{};
	  	
	  	var useRigthRuleForm = ({
				id : 'form',
				items : [{ type : 'text', label : '规则名称', fieldName : 'RULENAME', width : 220},
							{ type : 'html', html : '<hr>', fieldName : 'TIP1', width : 220},
							{ type : 'pick-grid', label : '开发团队', fieldName : 'TEAM_CODE',storesql:"select TEAM_CODE VALUES1,TEAM_NAME VALUES2 from meta_team where TEAM_CODE<>'"+this.teamcode+"'", width : 220},
							{ type : 'checkbox', label : '数据库', fieldName : 'DBNAME',storesql:"select dbname,CNNAME from metadbcfg where dbname<>'METADB'", width : 420  },
							{ type : 'text', label : '主题包含', fieldName : 'TOPICCODE', width : 220  } ,
							{ type : 'text', label : '表名包含', fieldName : 'OBJNAME', width : 220  } ,
							{ type : 'checkbox', label : '权限级别', fieldName : 'RIGTHLEVEL',storesql:'一级敏感,二级敏感,普通', width : 220  },
							{ type : 'html', html : '<hr>', fieldName : 'TIP2', width : 220},
							{ type : 'combox', label : '<b>授权类型</b>', fieldName : 'RIGTHLEVEL', storesql:'免授权,申请授权,不允许申请',width : 220  },
							],
				fieldChange:function(fieldName, newVal){ 
					  ruleObj[fieldName]=newVal;
				}
			});
			for(var i=0;i<useRigthRuleForm.items.length;i++){
				var item = useRigthRuleForm.items[i];
				if(ruleObj[item.fieldName]) item.value=ruleObj[item.fieldName];
			};
	       ai.showDialogForm(useRigthRuleForm,null,aftSave);
	  }, */
	  editToolsCfg:function(tooltype){
	   
	  	var aftSave=function(fieldVals){
	  		  var reamrk =_global_from.fields[2].getRawValue();
         		TeamPerMission.config.store.curRecord.set('RULETEXT',selVal);
         		TeamPerMission.config.store.curRecord.set('REMARK',reamrk||selVal );
         		TeamPerMission.config.store.commit();
         		TeamPerMission.reset(TeamPerMission.options);
	  	};
	   var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=TeamPerMission.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	var selVal=r.get('RULETEXT');
	  	var toolForm = ({
				id : 'form',
				title:'选择工具',
				items : [{ type : 'html', html : '选择工具' },
							{ type : 'html', html : '<hr>' },
							{ type : 'checkbox', label : ' ', fieldName : 'TOOLS',value:selVal,
								storesql:"select SOFTSYSCODE,SYSTEM_NAME from metasoftcfg where TYPE='"+tooltype+"'", 
							  width : 420  },
							],
				fieldChange:function(fieldName, newVal){ 
					selVal=newVal;
					  //ruleObj[fieldName]=newVal;
				}
			});
		 
	       ai.showDialogForm(toolForm,null,aftSave);
	  },
	  actFun:function(actId){
	  	 var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	 if(actId=="synatic") this.reset(this.options, true)
	  	 else  if(actId=="pickdbTopic")  this.selectDbTopic("",this.afterSelectDbTopic)
	  	 else  if(actId=="add")  this.addRule("add")
	  	 else  if(actId=="addSoftware")  this.selectSoftware("",this.afterSelectSoftware)
	  	 else  if(actId=="del")  this.deleteRule()
	  	 else  if(actId=="edit" &&(curItem.data.RULETYPE=="prodtools"|| curItem.data.RULETYPE=="mgrtools"))  this.editToolsCfg(curItem.data.RULETYPE)
	  	 else  if(actId=="edit")  this.editRule("edit")
	  },
	  afterSelectDbTopic:function(curItem,topicArray){
	  	console.log(topicArray);
	  	var rulecode = curItem.data.RULE_CODE;
	  	
	  	var curItemTopicsMap = {};
	  	function getItemTopics(node){
	  		var nodeChilds = node.getChildren();
	  		if(nodeChilds.length > 0){
	  			for(var j=0;j<nodeChilds.length;j++){
		  			getItemTopics(nodeChilds[j]);
		  		}
		  		var key = "key"+node.data.TOPICNAME;
		  		curItemTopicsMap[key] = node.data.TOPICNAME;
	  		}else{
	  			var key = "key"+node.data.TOPICNAME;
		  		curItemTopicsMap[key] = node.data.TOPICNAME;
	  		}
	  	}
	  	
	  	function checkTopicExists(topicCode){
	  		 var result=false;
	  		 var childrenArray = curItem.getChildren();
	  		 getItemTopics(curItem);
	  		 for(var i in curItemTopicsMap){
	  		 	 if(curItemTopicsMap[i]==topicCode){
	  		 	 	result=true;
	  		 	 	break;
	  		 	};
	  		};
	  		return result;
	  	};
	  	
	  	for(var i=0;i<topicArray.length;i++){
	  		
	  	       var addTopicCode=topicArray[i].RULECODE;
	  	       
	  	       if(checkTopicExists(addTopicCode)==true) continue;
	  	      // var newRuelCode = ai.getNewCode(TeamPerMission.config.store,"RULE_CODE",curItem.data.RULE_CODE+"-");//store,fieldname,pre,tabname
               
               var parentCode = topicArray[i].PARENTCODE;
               if(!parentCode) parentCode = curItem.data.RULE_CODE
               else parentCode=curItem.data.RULE_CODE+"-"+parentCode;
               	
              	var r=TeamPerMission.config.store.getNewRecord();
         		r.set('TEAM_CODE',TeamPerMission.teamcode);
         		r.set('RULE_CODE',curItem.data.RULE_CODE+"-"+topicArray[i].RULECODE);
         		r.set('PARENTCODE',parentCode);
         		r.set('RULETYPE','topic');
         		r.set('RULENAME',topicArray[i].RULENAME );
         		r.set('DBNAME',topicArray[i].DBNAME );
         		r.set('TOPICNAME',topicArray[i].RULECODE );
         		r.set('RULETEXT',topicArray[i].FUNC_ID);
         		r.set('REMARK',topicArray[i].DBNAME+","+topicArray[i].RULENAME);
         		TeamPerMission.config.store.add(r);
         		
	  	};
	  	TeamPerMission.config.store.commit();
        TeamPerMission.reset(this.options);
	  },
	  actRender:function(row,col){
	  	 var actnameArray="";
	  	 var ruleCode=row.RULE_CODE;
	  	 if(ruleCode=='R09') return "";
	  	 
	  	 if(row.RULETYPE=='database') actnameArray=['pickdbTopic','del']
	  	 else  if(row.RULETYPE=='ownertopic') actnameArray=['synatic'] 
	  	 else if(ruleCode=='R01') actnameArray=''
	  	 else if(ruleCode=='R02' || ruleCode=='R03' ||ruleCode=='R04') actnameArray=['add']
	  	 else if(ruleCode=='R09-01'||ruleCode=='R09-02') actnameArray=['addSoftware','del'] 
	  	 else  actnameArray=[/* 'edit', */'del'];
	  	  var html="";
	     if(actnameArray){
	     	 for(var i=0;i<actnameArray.length;i++){
	     	 	 var actid=actnameArray[i];
	     	 	 var actItem = TeamPerMission.actionItems[actid];
	     	 	 html+='<a id="'+actid+'" href="#" class="ruleact"><span class="'+actItem.icon+'"></span>'+actItem.title+'</a>&nbsp;&nbsp;'
	     	};
	    };
	    return html;
	  },
	  selectSoftware:function(selsql,callback){
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	softType = curItem.data.RULETYPE;
	 	  art.dialog({
   				 title: '软件选择:',
    				width: 860,height:300,
    				content: '<div style="height:300px;overflow:auto;" id="selecSoftwaretopic"></div>',
    				 init: function () {},
    				 ok: function () {
    					var selDataArray=softwaretreeGrid.getAllCheck();
    					if(selDataArray.length==0) {alert('你没有选择记录');return false;};
    					if(callback) return callback(curItem,selDataArray);
        				return true;
   					 },
   					 cancel:function(){}
			});
			 selsql="select * from metasoftcfg where type like '%"+softType+"%'";
	 		var softwareStrutStore=  new AI.JsonStore({
                sql:selsql.replace('{teamcode}',this.teamcode),
              //  key:"MODELCODE",
                pageSize:-1,
                table:"METASOFTCFG"  
        	});
	 		selsql = "select * from metamodel where state = 'on' ";
	 		var whereSql = "";
        	for(var i=0;i<softwareStrutStore.getCount();i++){
        		whereSql += " modelcode like '"+softwareStrutStore.getAt(i).get('SOFTSYSCODE')+"%'";
        		if(i<softwareStrutStore.getCount()-1) whereSql+=" or ";
        	}
        	if(whereSql){
        		selsql += " and ("+whereSql+")";
        	}
        	else{
        		selsql += " and 1=2";
        	}
    		toolStore =  new AI.JsonStore({
    			sql:selsql,
    			pageSize:-1,
    			key:"MODELCODE"
    		});
      		var config = {
				id : "selecSoftwaretopic",
				width : "800",
				renderTo : "selecSoftwaretopic",
				headerAlign : "left",
				headerHeight : "30",
				dataAlign : "left",
				indentation : "8",
				hoverRowBackground : "true",
				folderColumnIndex : "0",
				showcheck:true,
				columns : [ 
					{headerText : "工具编码", dataField : "MODELCODE", headerAlign : "center", width : "180" }, 
					{headerText : "工具名称", dataField : "MODELNAME", headerAlign : "center", width : "120" },
					{headerText : "工具描述", dataField : "REMARK", headerAlign : "center", width : "120"}
				],
				keyfield : "MODELCODE",
				pkeyfield : "PARENTCODE",
				titlefield : "MODELNAME",
				iconfield : "",
				store:toolStore,
				subtype : 'treegrid'
			};
           var softwaretreeGrid = new TreeGrid(config);
           softwaretreeGrid.show();
	 },
	 afterSelectSoftware:function(curItem,softwareArray){
	  	//console.log(softArray);
	  	var rulecode = curItem.data.RULE_CODE;
	  	var curItemSoftwareMap = {};
	  	function getItemSoftware(node){
	  		var nodeChilds = node.getChildren();
	  		if(nodeChilds.length > 0){
	  			for(var j=0;j<nodeChilds.length;j++){
		  			getItemSoftware(nodeChilds[j]);
		  		}
		  		var key = "key"+node.data.MODELNAME;
		  		curItemSoftwareMap[key] = node.data.MODELNAME;
	  		}else{
	  			var key = "key"+node.data.MODELNAME;
		  		curItemSoftwareMap[key] = node.data.MODELNAME;
	  		}
	  	}
	  	
	  	function checkSoftwareExists(modelCode){
	  		 var result=false;
	  		 //var childrenArray = curItem.getChildren();
	  		 getItemSoftware(curItem);
	  		 for(var i in curItemSoftwareMap){
	  		 	 if(curItemSoftwareMap[i]==modelCode){
	  		 	 	result=true;
	  		 	 	break;
	  		 	};
	  		};
	  		return result;
	  	};
	  	
	  	for(var i=0;i<softwareArray.length;i++){
	  		
	  	       var addSoftwareCode=softwareArray[i].MODELCODE;
	  	       
	  	       if(checkSoftwareExists(addSoftwareCode)==true) continue;
               
               var parentCode = softwareArray[i].PARENTCODE;
               if(!parentCode) parentCode = curItem.data.RULE_CODE
               else parentCode=curItem.data.RULE_CODE+"-"+parentCode;
               	
               	var tool = toolStore.getRecordByKey(softwareArray[i].MODELCODE)
              	var r=TeamPerMission.config.store.getNewRecord();
         		r.set('TEAM_CODE',TeamPerMission.teamcode);
         		r.set('RULE_CODE',curItem.data.RULE_CODE+"-"+softwareArray[i].MODELCODE);
         		r.set('RULENAME',softwareArray[i].MODELNAME);
         		r.set('RULETYPE',softType);
         		r.set('RULETEXT',tool.get("URL"));
         		r.set('PARENTCODE',parentCode);
         		r.set('TOPICNAME',softwareArray[i].MODELCODE);
         		r.set('REMARK',softwareArray[i].REMARK?softwareArray[i].REMARK:softwareArray[i].MODELNAME);
         		TeamPerMission.config.store.add(r);
         		
	  	};
	  	TeamPerMission.config.store.commit();
        TeamPerMission.reset(this.options);
	  },
	  selectDbTopic:function(selsql,callback){
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var dbname = curItem.data.DBNAME
	 	  art.dialog({
   				 title: '数据库主题选择:'+curItem.data.DBNAME,
    				width: 860,height:300,
    				content: '<div style="height:300px;overflow:auto;" id="selecdbtopic"></div>',
    				 init: function () {
     							//buildMetaTeamPerssion();
    				},
    				ok: function () {
    					var selDataArray=seltreeGrid.getAllCheck();
    					if(selDataArray.length==0) {alert('你没有选择记录');return false;};
    					if(callback) return callback(curItem,selDataArray);
        				return true;
   					 },
   					 cancel:function(){
   					}
			});
			 selsql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF from metadb_struct where DBNAME ='"+dbname+"'";
	 		var dbStrutStore=  new AI.JsonStore({
                sql:selsql.replace('{teamcode}',this.teamcode),
                key:"DBNAME,RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"  
        	});
      		var config = {
				id : "selecdbtopic",
				width : "800",
				renderTo : "selecdbtopic",
				headerAlign : "left",
				headerHeight : "30",
				dataAlign : "left",
				indentation : "8",
				hoverRowBackground : "true",
				folderColumnIndex : "0",
				showcheck:true,
				columns : [ 
					{headerText : "主题编号", dataField : "RULECODE", headerAlign : "center", width : "180" }, 
					{headerText : "数据库名", dataField : "DBNAME", headerAlign : "center", width : "120" },
					{headerText : "主题名称", dataField : "RULENAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}
				],
				keyfield : "RULECODE",
				pkeyfield : "PARENTCODE",
				titlefield : "RULENAME",
				iconfield : "",
				store:dbStrutStore,
				subtype : 'treegrid'
			};
           var seltreeGrid = new TreeGrid(config);
           seltreeGrid.show();
	 },
	 bindEvent:function(){
	 	
	 	$("#metaTeamPerssionInfo table tr td a.ruleact").click(function(event){
			$(this).parent().parent().click();
			var actId = $(this).attr("id");
			
			 event.stopPropagation();
			 TeamPerMission.actFun(actId);
			
			 return false;
		});
	},
	  init:function(options){
	  	 this.options=options;
	     this.teamcode=options.teamcode;
	     var dbStrutStore=  new AI.JsonStore({
                  sql:this.treesql.replace("{team_code}",options.teamcode),
                  key:"TEAM_CODE,RULE_CODE",
                  pageSize:-1,
                  table:"meta_team_permission"  
         });
        if(dbStrutStore.getCount()==0){
         
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R01');r.set('RULETYPE','ownertopic');r.set('RULENAME','工作目录主题');
        	dbStrutStore.add(r);
        	
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R02');r.set('RULETYPE','datauserrule');r.set('RULENAME','同库数据使用权限规则');
        	dbStrutStore.add(r);
        	
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R03');r.set('RULETYPE','datasendrule');r.set('RULENAME','跨库分发使用的规则');
        	dbStrutStore.add(r);
        	
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R04');r.set('RULETYPE','dataopenrule');r.set('RULENAME','数据服务平台使用规则');
        	dbStrutStore.add(r);
        	
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09');r.set('RULETYPE','tools');r.set('RULENAME','开通工具');
        	dbStrutStore.add(r);
        	
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09-01');r.set('PARENTCODE','R09');r.set('RULETYPE','prodtools');r.set('RULENAME','开发工具');
        	dbStrutStore.add(r);
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09-02');r.set('PARENTCODE','R09');r.set('RULETYPE','mgrtools');r.set('RULENAME','管理工具');
        	dbStrutStore.add(r);
        	dbStrutStore.commit();
        };
         $("#metaTeamPerssionInfo").empty();
         this.config.store=dbStrutStore;
         this.config.itemClick=this.itemClickEvent;
         this.config.columns[0].handler = this.ruleNameRender;
         this.config.columns[1].handler = this.actRender;
         this.config.columns[3].handler = this.remarkRender;
		this.ruleTreeGrid = new TreeGrid(this.config);
		this.ruleTreeGrid.show();
        this.bindEvent();
      },
	reset:function(options, isFromSyncButton){
      	if(!isFromSyncButton) {
      		this.init(this.options);
      		return;
      	}
      	//同步数据库
      	var self = this;
      	var sql = "select DBNAME VALUES1, CNNAME VALUES2, TEAM_CODE VALUES3 from DATA_TRANS_DATABASE where TEAM_CODE = '" + this.teamcode + "' and dbname not in (select DBNAME from META_TEAM_PERMISSION where TEAM_CODE = '" + this.teamcode + "' and ruletype = 'database')";
      	if(ai.getJsonStore(sql).getCount() == 0) {
      		alert("没有需要同步的数据库");
      		return;
      	}
      	var afterSelect = function(rs) {
      		if(rs.length == 0) {
      			alert("请至少选择一个需要同步的数据库！");
      			return false;
      		}
      		for(var i in rs) {
      			var r = rs[i];
      			var newRuelCode = ai.getNewCode(self.config.store,"RULE_CODE",'R01-');//store,fieldname,pre,tabname
				var newRec = self.config.store.getNewRecord();
				newRec.set('TEAM_CODE',self.teamcode);
				newRec.set('RULE_CODE',newRuelCode);
				newRec.set('PARENTCODE','R01');
				newRec.set('RULETYPE','database');
				newRec.set('RULENAME',r.get('VALUES1'));
				newRec.set('RULENAME',r.get('VALUES2')); 
				newRec.set('DBNAME',r.get('VALUES1')); 
				self.config.store.add(newRec);
      		}
      		self.config.store.commit();
      		self.init(self.options);
      	};
      	var selBox=new SelectBox({sql:sql, callback:afterSelect});
		selBox.show();
      	/*
		for(i=0;i<ds_teamdb.getCount();i++){
			var r=ds_teamdb.getAt(i);
			var exitst=false;
			for(var j=0;j< this.config.store.getCount();j++){
				var structRec = this.config.store.getAt(j);
				if(structRec.get('PARENTCODE')!='R01') continue;
				if(structRec.get('DBNAME')==r.get('DBNAME')){
					exitst=true;
				}
			};
			if(exitst==false){
				var newRuelCode = ai.getNewCode(this.config.store,"RULE_CODE",'R01-');//store,fieldname,pre,tabname
				var newRec = this.config.store.getNewRecord();
				newRec.set('TEAM_CODE',this.teamcode);
				newRec.set('RULE_CODE',newRuelCode);
				newRec.set('PARENTCODE','R01');
				newRec.set('RULETYPE','database');
				newRec.set('RULENAME',r.get('DBNAME'));
				newRec.set('RULENAME',r.get('CNNAME')); 
				newRec.set('DBNAME',r.get('DBNAME')); 
				this.config.store.add(newRec);
			};
		}
      	this.config.store.commit();
      	this.init(this.options);
		*/
	}	
};
	$(document).ready(function(){
		ai.loadWidget("dialog");
		
		var objtype="TEAM";
		var objname=paramMap.objname||'';
		var objXMLID=paramMap.xmlid||'';
		var runEnv=paramMap.runEnv || ''; //runEnv = mds表示数据库授权时要同时授权开发库和生产库
		if(runEnv=="mds"){
			var mdsStore = new AI.JsonStore({
				sql : "select * from metadbcfg",
				dataSource:"METADBS",
				pageSize:-1,
				key:"DBNAME"
			});
			var mdsTeamStore = new AI.JsonStore({
				sql:"select * from data_trans_database where team_code='"+objname+"'",
				dataSource:"METADBS",
				pageSize:-1,
				key:"TEAM_CODE,DBNAME",
				table:"DATA_TRANS_DATABASE"
			});
		}
	 
		var metasoft=new AI.Meta(objtype);
		
		function buildMetaBaseInfo(){
	 		var objAttrStore=ai.getStoreData("select * from metaobjcfg where objtype='"+objtype+"' order by seq");
	 		objDataStore=ai.getStoreData("select * from meta_team where team_code='"+objname+"'");
	 		console.log(objAttrStore);
	 		var html = '<fieldset> <table class="table"> <tbody>';
	 		var objdbRec=objDataStore[0];
	 		for(var i=0;i<objAttrStore.length;i++){
	 			var objAttrItem = objAttrStore[i];
	 			if(objdbRec.TEAM_TYPE=='1'){objdbRec.TEAM_TYPE='每表申请免授权'}
	 			if(objdbRec.TEAM_TYPE=='2'){objdbRec.TEAM_TYPE='规则授权'}
	 			if(objdbRec.TEAM_TYPE=='3'){objdbRec.TEAM_TYPE='免授权'}
	 			if(objdbRec.STATE=='on'){objdbRec.STATE='有效'}
	 			if(objdbRec.STATE=='off'){objdbRec.STATE='无效'}
	 			if(objdbRec.REMARK==null){objdbRec.REMARK=''}
	 			if(objdbRec.TEAM_MGR==null){objdbRec.TEAM_MGR=''}
	 			html+='<tr > <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME+'</th><td>'+objdbRec[objAttrItem.ATTRNAME]||""+' </td></tr>';
	 		};
	         html+='</tbody></table></fieldset>';              
	         $("#teambaseinfo").empty().append(html);                         
	 	};

	 	function buildTeamUserList(){
	 		$("#teamuserinfo").empty();
	 		var html = '<li class="list-group-item" USERNAME="{USERNAME}" style="min-height: 66px">'
				+ '<a class="thumb-sm pull-left m-r-sm" style="font-size:30px"> <span class="glyphicon glyphicon-user img-circle" aria-hidden="true"></span></a>'
				+ '<a class="clear"> <small class="pull-right"></small>  '
				+ '<strong class="block">{USECNNAME}, {USERNAME} </strong> '
				+ '<small>{REMARK}{DBUSER}{PHONE}{MAIL} </small></a>'
				+ '</li>';
			// var rolecode=teamRoleStore.curRecord.get('ROLE_CODE');	
			var userSql="select distinct a.TEAM_CODE,a.role_code, a.REMARK,b.USERNAME,b.USECNNAME ,b.PHONE,b.MAIL,b.DBUSER from meta_team_role_user a ,metauser b where a.username=b.username and a.team_code ='{teamcode}'";
			
			ds_teamUser = new AI.JsonStore({
				sql :userSql.replace('{teamcode}', objname),
				table:'meta_team_role_user',
				key:'TEAM_CODE,ROLE_CODE,USERNAME',
				pageSize : -1
			});

			var nameArr = [];
			for(var i=0;i<ds_teamUser.getCount();i++){
				var r=ds_teamUser.getAt(i);

				if(nameArr.indexOf(r.get("USERNAME")) == -1) {
					nameArr.push(r.get("USERNAME"));
				} else {
					continue;					
				}

				//var newHtml = html.replace("{USERROLE}",r.get("ROLE_CODE") )
				var newHtml =	html.replace("{USERNAME}",r.get("USERNAME")).replace("{USERNAME}",r.get("USERNAME"))
					.replace("{USECNNAME}",r.get("USECNNAME"));
					if(r.get("DBUSER")){
						newHtml=newHtml.replace("{DBUSER}",("<i class='fa fa-book'></i> 平台账号:"+r.get("DBUSER")+" ")||"");
					}else{
						newHtml=newHtml.replace("{DBUSER}","");
					}
					if(r.get("PHONE")){
						newHtml=newHtml.replace("{PHONE}",("<i class='fa fa-book'></i> 电话:"+r.get("PHONE")+" ")||"")
					}else{
						newHtml=newHtml.replace("{PHONE}","");
					}	
					if(r.get("REMARK")){
						newHtml=newHtml.replace("{REMARK}",("<i class='fa fa-book'></i> 工作描述:"+r.get("REMARK")+" ")||"")
					}else{
						newHtml=newHtml.replace("{REMARK}","");
					}	
					if(r.get("MAIL")){
						newHtml=newHtml.replace("{MAIL}",("<i class='fa fa-book'></i> 邮箱:"+r.get("MAIL")+" ")||"");
					}else{
						newHtml=newHtml.replace("{MAIL}","");
					}
				$("#teamuserinfo").append(newHtml);
			}
			$("#teamuserinfo .list-group-item").click( function() {
				$("#teamuserinfo .list-group-item").removeClass("active");
				$(this).addClass("active");
				var staffName=$(this).attr("USERNAME");
	            for(var i=0;i<ds_teamUser.getCount();i++){
					var r=ds_teamUser.getAt(i);
					if(r.get('USERNAME')==staffName){
						ds_teamUser.curRecord=r;break;
					}
				}
				return false;
			});
	 	};
        function buildTeamUserInfo(){
	 		var showStaffInfoDialog=function(acttype){
	  		$("#staffForm").empty();
	  		var roleName = "select t.ROLE_CODE,t.ROLE_NAME from meta_team_role t where t.team_code = '{teamCode}'".replace('{teamCode}',objname);
			var formcfg = ({
				id : 'form',
				store : ds_teamUser,      
				containerId : 'staffForm',
				items : [ { type : 'text', label : '英文名',notNull:'N', fieldName : 'USERNAME', width : 220, isReadOnly:acttype=='edit'?'y':'n'},
					{ type : 'text', label : '中文名', notNull:'N',fieldName : 'USECNNAME', width : 220  },
					{ type : 'text', label : '联系电话', fieldName : 'PHONE', width : 220  },
					{ type : 'text', label : '邮箱', fieldName : 'MAIL', width : 220  },
					{ type : 'text', label : '平台账号', fieldName : 'DBUSER', width : 220  },
					// { type : 'combox', label : '角色',notNull:'N', storesql:roleName, fieldName : 'ROLE_CODE', width : 220  },
					{ type : 'textarea', label : '备注', fieldName : 'REMARK', width : 420  } 
				],
				fieldChange:function(fieldName, newVal){
					var ds_metaMember = new AI.JsonStore({///租户成员表
						sql :"select USERNAME, USECNNAME, PASSWORD, REMARK, QQ, MSN, PHONE, MAIL, DBUSER, MD5PASS from METAUSER where USERNAME='"+newVal+"'",
						table:'METAUSER',
						key:'USERNAME'
					});
					if(fieldName==='USERNAME'){
						if(ds_metaMember.getCount()>0){
							ds_teamUser.curRecord.set("USERNAME",'')
	                        $("#staffForm #USERNAME").val('');
	                        alert("该英文名称已经存在,不能重复添加!");                       
						}
					}
					if(fieldName==='MAIL'){
						if(newVal.length!=0){
							var reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
							if(!reg.test(newVal)){
								alert("对不起，您输入的邮箱格式不正确!(例如:example@xx.com)");
							}
						}else{
							alert("请输入邮箱地址！");
						}
					}
					if(fieldName==='PHONE'){
						if(newVal.length!=0){
							var reg=/^\d{11}$/;
							if(!reg.test(newVal)){
								alert("对不起，您输入的联系电话格式不正确!(11位数字)");
							}
						}else{
							alert("请输入联系电话！");
						}
					}
				}
			});
			gloableUserFormcfg = formcfg; 
			var from = new AI.Form(formcfg);
			$('#staffModal #dialog-ok').attr("acttype", acttype);
			$('#staffModal').modal({
				show : true
			});
	   };
	   //取消 
	   $("#staffModal #dialog-cancel").click(function() {
			for(var i=0;i<ds_teamUser.getCount();i++){
				var _r = ds_teamUser.getAt(i);
				if(_r.get("TMP_ADD")==='y'){
					ds_teamUser.remove(_r);
				}
			}
			ds_teamUser.cache.save = [];
		 });
	   $("#staffModal #dialog-ok").click(function() {
			if ($('#staffModal #dialog-ok').attr('acttype') == 'add' || $('#staffModal #dialog-ok').attr('acttype') == 'edit') {
				   
					var items = gloableUserFormcfg.items;
					var keys = _.keys(ds_teamUser.curRecord.data);
					var _flag = true;
					var userName=ds_teamUser.curRecord.get("USERNAME");
					var memRecord = ds_teamUser.curRecord;	   
				    var ds_metaMember = new AI.JsonStore({///租户成员表
						sql :"select USERNAME, USECNNAME, PASSWORD, REMARK, QQ, MSN, PHONE, MAIL, DBUSER, MD5PASS from METAUSER where USERNAME='"+memRecord.get('USERNAME')+"'",
						table:'METAUSER',
						key:'USERNAME'
					}); 
					//修改了成员信息表单的非空验证如下2015-09-08
					for(var i=0;i<items.length;i++){
						var col = ds_teamUser.curRecord.get(items[i].fieldName);
						if((items[i].fieldName!='REMARK'&&items[i].fieldName!='PHONE'&&items[i].fieldName!='MAIL'&&items[i].fieldName!='DBUSER')&&(!col||col.length<1)&&(i<items.length)){
							_flag = false;
							alert(items[i].label+"不能为空！");
						}
						if(items[i].fieldName==='USERROLE'&&col==='角色'){
							_flag = false;
							alert("请选择角色类型！");
						}
						if(_flag===false){return;}
					}
	
				   ds_teamUser.curRecord.set('TMP_ADD','n');
	         var role_name = new AI.JsonStore({///租户成员表
							sql :"SELECT ROLE_NAME FROM meta_team_role WHERE team_code ='"+objname+"' AND ROLE_CODE='"+memRecord.get('ROLE_CODE')+"'",
							table:'meta_team_role',
							key:'TEAM_CODE,ROLE_CODE',
							pageSize : -1
						}); 
	                 if(role_name.getCount()>0){
	                    ds_teamUser.curRecord.set("ROLE_NAME",role_name.getAt(0).get("ROLE_NAME"));
	                 } 
	
	               if($('#staffModal #dialog-ok').attr('acttype') == 'edit'){
	                  var r=ds_teamUser.curRecord; 
	                  var delete_sql="DELETE FROM meta_team_role_user WHERE ROLE_CODE='"+old_edit_groupcode+"' AND username='"+old_edit_username+"'";
	                  var insert_sql="INSERT INTO meta_team_role_user (USERNAME,ROLE_CODE,TEAM_CODE,REMARK) VALUES ('"+r.get('USERNAME')+"','"+r.get('ROLE_CODE')+"','"+ objname +"','"+r.get('REMARK')+"')";
	 		          		ai.executeSQL(delete_sql);                
	                  ai.executeSQL(insert_sql);
	               }else if($('#staffModal #dialog-ok').attr('acttype') == 'add'){
	                  ds_teamUser.commit();
	               }
				   
				   buildTeamUserList();
				   ///同步人员身份信息
				  if(ds_metaMember.getCount()==0){
				  	   var userRecord=ds_metaMember.getNewRecord();
				  	   userRecord.set('USERNAME',memRecord.get('USERNAME'));
				  	   userRecord.set('USECNNAME',memRecord.get('USECNNAME'));
				  	   userRecord.set('REMARK',memRecord.get('REMARK'));
				  	   userRecord.set('PHONE',memRecord.get('PHONE'));
				  	   userRecord.set('MAIL',memRecord.get('MAIL'));
				  	   userRecord.set('DBUSER',memRecord.get('DBUSER'));
				  	    var _URL="/"+contextPath+"/encrypt?password="+memRecord.get('USERNAME');
						 var newpass=ai.remoteData(_URL,false);
						 newpass = newpass.trim();
						userRecord.set('PASSWORD',newpass);
						userRecord.set('MD5PASS',newpass);
				  	   ds_metaMember.add(userRecord);
				  	   ds_metaMember.commit();
				  }else{
				  	   var userRecord=ds_metaMember.getAt(0);
				  	    userRecord.set('USERNAME',memRecord.get('USERNAME'));
				  	   userRecord.set('USECNNAME',memRecord.get('USECNNAME'));
				  	   userRecord.set('REMARK',memRecord.get('REMARK'));
				  	   userRecord.set('PHONE',memRecord.get('PHONE'));
				  	   userRecord.set('MAIL',memRecord.get('MAIL'));
				  	   userRecord.set('DBUSER',memRecord.get('DBUSER'));
				  	   ds_metaMember.commit(); 
				  };
			}
			$('#staffModal').modal("hide");
			buildTeamUserList();
		});
	   
	 		//创建人员
	    $("#createteamuser").click(function(){
	    	var r=ds_teamUser.getNewRecord();
			   r.set("USERNAME",'');
			   r.set("USECNNAME",'');
			   r.set("PHONE",'');
			   r.set("MAIL",'');
			   r.set("DBUSER",'');
			   r.set("ROLE_NAME",roleInfo['ROLE_NAME']);
			   r.set("REMARK",'');
			   r.set('TMP_ADD','y');
			   r.set("GROUPCODE",roleInfo['ROLE_CODE']);
			   ds_teamUser.add(r);
			   ds_teamUser.curRecord=r;
		 	  showStaffInfoDialog("add");
	    });
	    
	    var afterSelect=function(rs){
	    	    // var rolecode = teamRoleStore.curRecord.get('ROLE_CODE');
			 	for(var i=0;i<rs.length;i++){
			 		  var r=ds_teamUser.getNewRecord();
			 		  
			 		  r.set("TEAM_CODE",objname);
			 		  r.set("ROLE_CODE","default");
			 		  r.set("USERNAME",rs[i].get('VALUES1'));
			 		  r.set("REMARK",rs[i].get('VALUES2'));
			 		  ds_teamUser.add(r);
			 	};
			 	ds_teamUser.commit();
			 	buildTeamUserList();
			}; 
	    //选择添加人员
	    $("#selectteamuser").click(function(){
	    	// var selSql="select username VALUES1,usecnname values2,REMARK VALUES3 from metauser where username not in (select username from metagroupuser a, metagroup b where a.groupcode = b.groupcode and b.team_code  ='"+objname+"')";
	    	var selSql = "select username VALUES1,usecnname values2,REMARK VALUES3 from metauser where username not in (select distinct username from meta_team_role_user where team_code = '" + objname + "')";
	 	   	var selBox=new SelectBox({sql:selSql,callback:afterSelect});
     	 	selBox.show();
	    });
	    //删除
	    $("#deleteteamuser").click(function(){
	    	var r=ds_teamUser.curRecord;
		   	if(window.confirm("确定删除租户:"+r.get('USECNNAME')+"吗?")){
				   	  ds_teamUser.remove(r);
				   	  ds_teamUser.commit();
				   	  buildTeamUserList();
				   	  ds_teamUser.curRecord = "";
				   	  alert('成功删除');
				}; 
	    });
	    //修改
	    $("#editteamuser").click(function(){
	    	old_data=ds_teamUser.curRecord;
		 		old_edit_groupcode=old_data.get("ROLE_CODE");
		 		old_edit_username=old_data.get("USERNAME");
			 	showStaffInfoDialog("edit"); 
	    });
	 		
	 	};
	 	function buildDbList(){
	 		$("#transDbInfo").empty();
	 		myDBsql = "SELECT DBNAME,CNNAME,LOCALALIAS,DBTYPE,JNDINAME,STATE,TEAM_CODE FROM data_trans_database WHERE team_code='{team_code}'";
	 		ds_teamdb = new AI.JsonStore({///数据库列表
				sql : myDBsql.replace('{team_code}', objname),
				table:'DATA_TRANS_DATABASE',
				key:'TEAM_CODE,DBNAME,DBTYPE',
				pageSize : -1
			});
	 		var config={
				bAutoWidth:true,
				store:ds_teamdb,
				pageSize: -1,
				containerId:'transDbInfo',
				nowrap:true,
				showcheck:false,
				columns:[
					{header: "数据库", width:80,dataIndex: 'DBNAME', sortable: true},
					{header: "中文名", width:120, dataIndex: 'CNNAME', sortable: true},
					{header: "本地别名", width:80, dataIndex: 'LOCALALIAS'},
					{header: "类型", width:74, dataIndex: 'DBTYPE'}
					// {header: "帐号名称", width:74, dataIndex: 'USERNAME'}
				]
			};
			dbListgrid =new AI.Grid(config);
			
	 	};
	 	var hiveDbname = null;
	 	function buildDbInfo(){
	 		var showDBInfoDialog = function(acttype){
	 			if(runEnv=="mds"){
	 				mdsTeamStore.cache.save = [];
		 			mdsTeamStore.cache.update = [];
		 			mdsTeamStore.cache.remove = [];
	 			}
	 			//获取hive资源分配数据库
	 			var defaultDBStore = new AI.JsonStore({//动态查询hive库连接信息
			    	sql : "select rowcode,rowname from metaedimdef where dimcode='DIM_HIVE_DBNAME' and rowcode='DBNAME'"
				});
  				var defaultDBRecord = defaultDBStore.getAt(0);
  				var hiveUsername = null;
  				if(defaultDBRecord){
  					hiveDbname = defaultDBRecord.get("ROWNAME");
  					var hadoopStore = new AI.JsonStore({//动态查询hive库连接信息
  				    	sql : "select res_cfg from meta_team where team_code='"+objname+"'"
  					});
  					var hadoopRecord = hadoopStore.getAt(0);
  					if(hadoopRecord && hadoopRecord.get("RES_CFG")){
  						var res_cfg = JSON.parse(hadoopRecord.get("RES_CFG")) || {};
  						hiveUsername = res_cfg.haddop_user;
  					}
  				}
	 			
	 			var items = null;
	 			if(runEnv == "mds"){
	 				items = [
	 						{type : 'combox',editable:'N', label : '数据库', notNull:'N',fieldName : 'DBNAME', storesql : "select DBNAME,CNNAME from metadbcfg"},
	 						{type : 'text', label : '本地别名', fieldName : 'LOCALALIAS'},
	 						{type : 'text', label : '开发环境URL', fieldName : 'MD_URL',width:350},
	 						{type : 'text', label : '开发环境用户名', fieldName : 'MD_USERNAME'},
	 						{type : 'text', label : '开发环境密码', fieldName : 'MD_PASSWORD'},
	 						{type : 'text', label : '生产环境URL', fieldName : 'MDS_URL',width:350},
	 						{type : 'text', label : '生产环境用户名', fieldName : 'MDS_USERNAME'},
	 						{type : 'text', label : '生产环境密码', fieldName : 'MDS_PASSWORD'}
	 					]
	 			}else{
	 				items = [
							{type : 'combox',editable:'N', label : '数据库', notNull:'N',fieldName : 'DBNAME', storesql : "select DBNAME,CNNAME from metadbcfg"},
							{type : 'text', label : '本地别名', fieldName : 'LOCALALIAS'},
							{type : 'text', label : 'URL', fieldName : 'MD_URL',width:350},
	 						{type : 'text', label : '用户名', fieldName : 'MD_USERNAME'},
	 						{type : 'text', label : '密码', fieldName : 'MD_PASSWORD'}
						]
	 			}
				$("#dbForm").empty();
				var formcfg = ({
					id : 'form',
					// store : ds_teamdb,
					containerId : 'dbForm',
					items : items,
					fieldChange:function(fieldName, newVal) {
						// for(var i=0; i<ds_teamdb.getCount(); i++) {
						// 	var r = ds_teamdb.getAt(i);
						// 	alert(r.get("DBNAME"));
						// }
						if(newVal==''||newVal==null){
							alert("请选择数据库！");
							ds_teamdb.cache.save = [];
							ds_teamdb.cache.update = [];
							ds_teamdb.cache.remove = [];
							return;
						}
						if(fieldName==='DBNAME'){
							var store = new AI.JsonStore({///数据库列表
								sql : "select * from metadbcfg where dbname = '"+newVal+"'"
							});
							if(store.getCount()==0) return;
							
							var dbname = store.getAt(0).get('DBNAME');
							var cnname = store.getAt(0).get('CNNAME');
							var jndiname = store.getAt(0).get('JNDINAME');
							var dbusername=store.getAt(0).get('USERNAME');
							var dbpassword = store.getAt(0).get('PASSWORD');
							var driverclass = store.getAt(0).get('DRIVERCLASSNAME');
							var dburl = store.getAt(0).get('URL');
							var dbtype = store.getAt(0).get('ALIAS');;
							var nondbname=false;
							if(dbname == hiveDbname && !hiveUsername && !window.confirm("分配的数据库为hive资源库，未分配该团队hive资源，是否继续")){
								return;
							}
							$("#MD_URL").val(dburl);
							if(runEnv == "mds"){
								var mdsRecord = mdsStore.getRecordByKey(dbname);
								var mdsUrl = mdsRecord.get("URL");
								//hive资源分配连接替换最后的组信息
						    	if(hiveDbname == dbname && hiveUsername){
						    		var urls = mdsUrl.split("/");
						    		mdsUrl = urls[0] +"//"+urls[2]+"/"+hiveUsername;
						    		$("#MDS_USERNAME").val(hiveUsername);
									$("#MDS_PASSWORD").val(hiveUsername);
						    	}
								$("#MDS_URL").val(mdsUrl);
							}else if(hiveDbname == dbname && hiveUsername){
								var urls = dburl.split("/");
								$("#MD_URL").val(urls[0] +"//"+urls[2]+"/"+hiveUsername);
								$("#MD_USERNAME").val(hiveUsername);
								$("#MD_PASSWORD").val(hiveUsername);
							}
							
							for(var i =0 ; i< ds_teamdb.getCount(); i++){
								var r = ds_teamdb.getAt(i);
								if(dbname == r.get("DBNAME")&&objname==r.get("TEAM_CODE")&&'y'!=r.get("TMP_ADD")){
									nondbname=true;
									break;
								}
							}
	
							if(nondbname){
								alert("该团队下已经有该数据库,请重新选择！！");
								$("#dbForm #DBNAME").val('');
								ds_teamdb.cache.save = [];
							    ds_teamdb.cache.update = [];
							    ds_teamdb.cache.remove = [];
								return;
							}
							ds_teamdb.curRecord.set('CNNAME',cnname);
							ds_teamdb.curRecord.set('DBNAME',dbname);
							ds_teamdb.curRecord.set('JNDINAME',jndiname);
							ds_teamdb.curRecord.set('DRIVERCLASSNAME',driverclass);
							ds_teamdb.curRecord.set('URL',dburl);
							ds_teamdb.curRecord.set('DBTYPE',dbtype);
							ds_teamdb.curRecord.set('TEAM_CODE',objname);
							ds_teamdb.curRecord.set('USERNAME', dbusername);
							ds_teamdb.curRecord.set('PASSWORD', dbpassword);
						}
					}
				});
				gloableDbCfg = formcfg;
				var from = new AI.Form(formcfg);
				$('#dbModal #db-dialog-ok').attr("acttype", acttype);
				$('#dbModal').modal({
					show : true,
					backdrop : 'static'
				});
			};

			$('#db-dialog-ok').on('click', function(){
			    var dbname=ds_teamdb.curRecord.get("DBNAME");	
			    var localalias = $("#dbModal #LOCALALIAS").val();
			    ds_teamdb.curRecord.set("LOCALALIAS",localalias);
			    if(runEnv=="mds"){
					if(!mdsStore.getRecordByKey(dbname)){
						alert("生产库未配置该数据库");
						return;
					}
				}
			    if(dbname.trim()==''||dbname.trim()==null){
		           alert("请选择数据库");
		           ds_teamdb.cache.save = [];
				   ds_teamdb.cache.update = [];
				   ds_teamdb.cache.remove = [];
		           return;
			    }
			    var md_username = $("#MD_USERNAME").val();
			    var md_password = $("#MD_PASSWORD").val();
			    var mds_username = $("#MDS_USERNAME").val();
			    var mds_password = $("#MDS_PASSWORD").val();
			    var warnMsg = "";
			    if(runEnv == "mds"){
			    	if(!md_username || !md_password){
			    		warnMsg += "未录入开发环境用户名或密码，采用默认用户名密码。";
			    	}
			    	if(!mds_username || !mds_password){
			    		warnMsg += "未录入生产环境用户名或密码，采用默认用户名密码。";
			    	}
			    }else{
			    	if(!md_username || !md_password){
			    		warnMsg += "未录入用户名或密码，采用默认用户名密码。";
			    	}
			    }
			    if(warnMsg && !window.confirm(warnMsg+"是否继续") ){
			    	return;
			    }
			    var mdUrl = $("#MD_URL").val().trim();
			    if(mdUrl){
			    	ds_teamdb.curRecord.set("URL",mdUrl);
			    }
			    if(md_username && md_password){
			    	md_password = ai.remoteData("/"+contextPath+"/crypto/encrypt/des?message="+encodeURIComponent(md_password));
			    	ds_teamdb.curRecord.set('USERNAME', md_username);
					ds_teamdb.curRecord.set('PASSWORD', md_password);
			    }
				
				if(runEnv=="mds"){
					var record = mdsTeamStore.getRecordByKey(objname+","+dbname);
					var mdsRecord = mdsStore.getRecordByKey(dbname);
					if(!record){
						record = mdsTeamStore.getNewRecord();
						mdsTeamStore.add(record);
						record.set("DBNAME",dbname);
					}
					record.set("CNNAME",mdsRecord.get("CNNAME"));
					record.set("DBTYPE",mdsRecord.get("ALIAS"));
					record.set("JNDINAME",mdsRecord.get("JNDINAME"));
					record.set("LOCALALIAS",localalias);
					var mdsUrl = $("#MDS_URL").val().trim();
					if(mdsUrl){
						record.set("URL",mdsUrl);
					}else{
						record.set("URL",mdsRecord.get("URL"));
					}					
					record.set("DRIVERCLASSNAME",mdsRecord.get("DRIVERCLASSNAME"));
					record.set("TEAM_CODE",objname);
					record.set("STATE","on");
					if(mds_username && mds_password){
				    	mds_password = ai.remoteData("/"+contextPath+"/crypto/encrypt/des?message="+encodeURIComponent(mds_password));
				    	record.set('USERNAME', mds_username);
				    	record.set('PASSWORD', mds_password);
				    }else{
				    	record.set("USERNAME",mdsRecord.get("USERNAME"));
						record.set("PASSWORD",mdsRecord.get("PASSWORD"));
				    }
					mdsTeamStore.commit();
					mdsTeamStore.select();
				}
				
				var result = ds_teamdb.commit();
				result = JSON.parse(result);
				if(result != true && result.success != true){
					alert("分配团队数据库失败");
					return;
				}
				ds_teamdb.select();
				alert("数据库添加成功");
				// buildMetaTeamPerssion();
				$('#dbModal').modal("hide");
			});

			$('.db-dialog-cancel').on('click', function(){
				for(var i=0;i<ds_teamdb.getCount();i++){
					var _r = ds_teamdb.getAt(i);
					if(_r.get('TMP_ADD')==='y'){
						ds_teamdb.remove(_r);
					}
				}
				$('#dbModal').modal("hide");
			});
	 
			$("#selectDbInfo").on('click', function(){
				var r=ds_teamdb.getNewRecord();
				ds_teamdb.add(r);
				r.set('TMP_ADD', 'y');
				r.set('TEAM_CODE', objname);
				r.set('STATE', 'on');
				r.set('DBNAME',' ');
				r.set('USERNAME','');
				r.set('PASSWORD','');
				ds_teamdb.curRecord=r;
				showDBInfoDialog();
			});

			$("#deleteDbInfo").on('click',function(){//删除库权限
			 	var r = ds_teamdb.curRecord;
			 	var dbname = r.get("DBNAME");
			 	if(r&&confirm("确认删除数据库" + dbname + "吗？")) {
			 		ai.executeSQL("delete from DATA_TRANS_DATABASE where TEAM_CODE='" + objname + "' and DBNAME='" + dbname + "'");
			   			
			   		var sql="delete from meta_team_permission where team_code='"+objname+"' and dbname='"+dbname+"'";
			   		ai.executeSQL(sql);
			 		ds_teamdb.select();
			 		//ds_dbuser.select();
			 		if(runEnv == "mds"){
			 			ai.executeSQL("delete from DATA_TRANS_DATABASE where TEAM_CODE='" + objname + "' and DBNAME='" + dbname + "'",null,"METADBS");
			 			mdsTeamStore.select();
			 		}
			 	} else if(!r) {
			 		alert("必须选中一条数据才能删除！");
			 	}
			});

			// function syncSelectedUser(logic_dbname) {
			// 	var delSql = "delete from data_trans_database where logic_dbname = '" + logic_dbname + "' and team_code = '" + objname + "' and username is not null";
			// 	ai.executeSQL(delSql);

			// 	var selected = userListgrid.getCheckedRows();
			// 	for(var i=0;i<selected.length;i++){
			// 	 		var username = selected[i].get('USERNAME');
			// 	 		var password = selected[i].get('PASSWORD');
			// 	 		var url = selected[i].get('URL');
			// 	 		var insSql = "insert into data_trans_database (DBNAME,LOGIC_DBNAME,CNNAME,DBTYPE,USERNAME,PASSWORD,URL,JNDINAME,STATE,TEAM_CODE) select distinct DBNAME,LOGIC_DBNAME,CNNAME,DBTYPE,USERNAME,PASSWORD,URL,JNDINAME,STATE, '" + 
			// 	 			objname + "' TEAM_CODE from data_trans_database where LOGIC_DBNAME = '" + logic_dbname +
			// 	 			"' and USERNAME = '" + username + "' and team_code is null";

			// 	 		ai.executeSQL(insSql);

			// 	 		var updateSql = "update data_trans_database set DBNAME = '" + objname + logic_dbname + username + "' where team_code = '" + objname + "' and logic_dbname = '" + logic_dbname + "' and username = '" + username + "'"; 
			// 	 		ai.executeSQL(updateSql);
			// 	}
			// 	ds_dbuser.select();
			// }

	 	}

	 	$("#editUserInfo").on('click', function() {
			var r = ds_dbuser.curRecord;
			if(!r) {
				return ;
			}
			var username = $("#user-username").val();
			var password = $("#user-password").val();
			var url = $("#user-url").val();

			password = cryptoPassword(password, 'encrypt');

			r.set('USERNAME', username);
			r.set('PASSWORD', password);
			r.set('URL', url);
			ds_dbuser.commit();
			alert('修改成功！');
		});

	 	var cryptoPassword = function(val, method) {
	 		var pwd = '密码获取失败';
	 		$.ajax({
				url:"/"+contextPath+"/crypto/" + method,
				data:{message: val},
				async: false,
				success:function(data, status){
					//alert(status);
					if(status=='success'){
						pwd = data.trim();
					}
				}
			});
			return pwd;
	 	}

		function buildTabList() {
			$("#tabInfo").empty();
			var _rowClickFunc = function (rowdata){
				// curdata= rowdata;
			};
			var _rowdblClickFunc = function(val,rowdata){
				// if(rowdata){
				// 	parent.loadTabStruct(rowdata.get('OBJNAME'),'',rowdata.get('READ_PARA'));
				// }
				// return false;
			};
			var tabDBName = ai.getStoreData("select DBNAME,CNNAME from metadbcfg");
			var getDBCNName = function(record,val){
				for (var i =0; i < tabDBName.length; i++) {
					if (val == tabDBName[i]["DBNAME"]) {
						return tabDBName[i]["CNNAME"]
					};
				};
				return val;
			};
			var tabUserName = ai.getStoreData("select USERNAME,USECNNAME from metauser");
			var getUserCNName = function(record,val){
				for (var i =0; i < tabUserName.length; i++) {
					if (val == tabUserName[i]["USERNAME"]) {
						return tabUserName[i]["USECNNAME"]
					};
				};
				return val;
			};
			var _auditStatFunc = function(record,val){
				var _status;
				switch(val){
					case 'apply-fail': _status='申请失败';break;
					case 'applying':   _status='申请中';break;
					case 'audit-pass': _status='审批通过';break;
					case 'audit-fail': _status='审批不通过';break;
					case 'grant-pass': _status='已授权';break;
					case 'grant-fail': _status='系统权限分配失败';break;
					default          : _status='未申请';break;
				}
				return _status;
			};

	 		var myTabSql = "select distinct a.XMLID, a.TEAM_CODE,b.dbname,objname,b.datacnname,apply_user,apply_time,audit_status,read_para,confine_para from META_TEAM_OBJECT a,tablefile b where a.objname=b.dataname and a.AUDIT_STATUS='grant-pass' and a.TEAM_CODE='" + objname + "'";

			ds_tab = new AI.JsonStore({///数据列表
				sql : myTabSql,
				table:'META_TEAM_OBJECT',
				key:'TEAM_CODE,OBJNAME',
				pageSize : 20
			});

	 		var config={
				bAutoWidth:true,
				store:ds_tab,
				//pageSize:15,
				containerId:'tabInfo',
				nowrap:true,
				showcheck:true,
				rowclick:_rowClickFunc,
				celldblclick:_rowdblClickFunc,
				columns:[
					{header: "数据库", width:80,dataIndex: 'DBNAME', sortable: true,render:getDBCNName},
					{header: "表名", width:120, dataIndex: 'OBJNAME', sortable: true},
					{header: "中文名", width: 105, dataIndex: 'DATACNNAME', sortable: true },
					{header: "权限级别", width:74, dataIndex: 'READ_RIGHT'},
					{header: "敏感字段", width:74, dataIndex: 'READ_PARA'},
					{header: "受限制字段", width:74, dataIndex: 'CONFINE_PARA'},
					{header: "操作人", width:74, dataIndex: 'APPLY_USER',render:getUserCNName},
					{header: "状态", width:74, dataIndex: 'AUDIT_STATUS',render:_auditStatFunc}
				]
			};
			tabGrid =new AI.Grid(config);
		}

		function buildAPITree() {
			$("#APITree").empty();

			var setting = {
				view: {selectedMulti: false},
				check: {enable: true},
				data: {simpleData: {enable: true}}
			};

			var teamPermission="select DISTINCT d.* FROM (	"+
				"SELECT DISTINCT a.APPLY id, 'root'  pId,A.APPLY NAME ,CASE WHEN B.FUNC_CODE IS NULL THEN 0 ELSE 1 END CHECKED ,'' FUNC_CODE "+
				"FROM proc_func_def_java a LEFT JOIN meta_team_func B "+
				 "ON A.FUNC_CODE=B.FUNC_CODE AND B.TEAM_CODE='{TEAMCODE}'  "+
				"UNION SELECT  B.MEMO id, CASE WHEN B.APPLY IS NULL THEN 'root' ELSE B.APPLY END pId,b.MEMO NAME ,CASE WHEN  "+
				"C.FUNC_CODE IS NULL THEN 0 ELSE 1 END CHECKED ,b.func_code FROM proc_func_def_java B  "+
				"LEFT JOIN meta_team_func C  "+
				"ON B.FUNC_CODE=C.FUNC_CODE AND C.TEAM_CODE='{TEAMCODE}') D  WHERE D.ID IS NOT NULL ORDER BY D.PID";

			var ds_api = new AI.JsonStore({
				sql : teamPermission.replace('{TEAMCODE}', objname).replace('{TEAMCODE}', objname),
				pageSize : -1
			});

			var buildZTree = function(models){
				var zNodesNew = [];
				if(models&&models.length>1){
					var n=0;
					for(var i=0;i<models.length;i++){
						var val = models[i];
						// if(val.ID == '5.数组&变量&逻辑') {
						// 	continue;
						// }
						zNodesNew.push({id:val.ID, pId:val.PID,name:val.ID,funCode:val.FUNC_CODE,checked:val.CHECKED==1?true:false});
					}
					$("#APITree").empty();
					$.fn.zTree.init($("#APITree"), setting, zNodesNew);
					// $.fn.zTree.getZTreeObj("APITree").expandAll(true);
				}else{
					$("#APITree").append("找不到数据！");
				}
			};

			ds_api.on('dataload',function(){
				buildZTree(ds_api.root);
			});
			ds_api.select();

			$("#saveAPI").on('click',function() {
				var delSql="delete from meta_team_func WHERE team_code='"+objname+"'";
				ai.executeSQL(delSql);
				var sql ="select FUNC_CODE,team_code ,STATE from meta_team_func ";
				var store= new AI.JsonStore({
					sql:sql,
					pageSize:-1,
					table:'meta_team_func',
					key:'FUNC_CODE,team_code',
					dataSource:'METADB'
				});
					   	
				var zTree = $.fn.zTree.getZTreeObj("APITree");
				var nodes = zTree.getCheckedNodes();
				for (var i=0, l=nodes.length; i<l; i++) {
					if(!nodes[i].pId) {
						continue;
					}
					var record=store.getNewRecord();
					if(nodes[i].funCode == null || nodes[i].funCode == '') continue;;
					record.set("FUNC_CODE",nodes[i].funCode);
					record.set("team_code", objname);
					record.set('STATE','1');
					store.add(record);
				}
				var rs = store.commit(true);
				var rsJson = $.parseJSON(rs);
				alert(rsJson.msg?rsJson.msg:'保存成功');
			});
		};

		function buildTeamFlow(){
			var ds_teamFlow = new AI.JsonStore({
	 			sql:"select t.team_code,t.flowcode,q.remark,q.flowname,t.state_date,t.xmlid from meta_team_flow t join devwkflow q on t.flowcode=q.flowcode where t.team_code='"+objname+"'",
	 			table:'meta_team_flow',
	 			key:'XMLID'
	 		});
	 		function addTeamFlowRole(flowcode){
		 		var ds_teamFlowRole = new AI.JsonStore({
		 			sql:"select * from meta_team_flow_role where team_code='"+objname+"' and flowcode='"+flowcode+"'",
		 			key:'ROLENAME,TEAM_CODE,FLOWCODE',
		 			table:'meta_team_flow_role'
		 		});
		 		var ds_flowRole = ai.getJsonStore("select * from devwkflow_role where flowcode='"+flowcode+"' and roleinditype='团队定义'");
		 		//删除
		 		for(var i = 0 ; i < ds_teamFlowRole.getCount() ; i++ ){
		 			var rec = ds_teamFlowRole.getAt(i) , isdelte = true ;
		 			for( var  j = 0 ; j < ds_flowRole.getCount() ; j++ ){
		 				if(ds_flowRole.getAt(j).get('ROLENAME')==rec.get('ROLENAME')) {
		 					isdelte = false ;
		 					break;
		 				};
		 			};
		 			if(isdelte) ds_teamFlowRole.remove(rec);
		 		}
		 		for(var i = 0 ; i < ds_flowRole.getCount() ; i++){
		 			var rec = ds_flowRole.getAt(i) ;
		 			var teamRec = ds_teamFlowRole.getRecordByKey(rec.get('ROLENAME')) ;
		 			if(teamRec) continue;
		 			var _rec = ds_teamFlowRole.getNewRecord() ;
		 			_rec.set('ROLENAME',rec.get('ROLENAME')) ;
		 			_rec.set('TEAM_CODE',objname) ;
		 			_rec.set('FLOWCODE',flowcode) ;
		 			_rec.set('XMLID',ai.guid()) ;
		 			_rec.set('ROLEPOINTTYPE','团队定义') ;
		 			ds_teamFlowRole.add(_rec);
		 		};
		 		ds_teamFlowRole.commit();
	 		};
			$('#addteamflow').off('click').on('click',function(){
				function afterAddOK(rs){
					for(var i=0;i<rs.length;i++){
				 		var r=ds_teamFlow.getNewRecord();
				 		r.set("TEAM_CODE",objname);
				 		r.set("FLOWCODE",rs[i].get('VALUES1'));
				 		r.set("STATE",'1');
				 		r.set("STATE_DATE",new Date().format("yyyy-mm-dd hh:mm:ss"));
				 		r.set("XMLID",ai.guid());
				 		ds_teamFlow.add(r);
				 		addTeamFlowRole(rs[i].get('VALUES1')) ;
				 	};
				 	ds_teamFlow.commit();
				 	buildTeamFlow();
				};
		    	var selSql = "select flowcode VALUES1,flowname values2,REMARK VALUES3 from devwkflow where state='on' and apply_range='team' and flowcode not in(select flowcode from meta_team_flow where team_code='"+objname+"')";
		 	   	var selBox=new SelectBox({sql:selSql,callback:afterAddOK});
	     	 	selBox.show();
	     	 	$('#selectgrid_page li a.pre').css('display','none');
          		$('#selectgrid_page li a.next').css('display','none');
          		$('#selectgrid_page li input').css('display','none');
          		$('#selectgrid_page li botton').css('display','none');
			});
			$('#delteamflow').off('click').on('click',function(){
				var selected = $('#teamflowinfo .list-group-item.active') ;
				if( selected.length == 0 ) {
					alert('请选择你要删除的流程');
					return ;
				}
				var xmlid = selected.attr('xmlid') ,record = ds_teamFlow.getRecordByKey(xmlid);
				if(window.confirm('你确定要删除名为：'+record.get('FLOWNAME')+'的流程吗？')){
					ds_teamFlow.remove(record);
					ds_teamFlow.commit();
					buildTeamFlow();
				}
			});
			function getFlowHtml(store){
		 		var htmltpl='<li class="list-group-item" xmlid="{xmlid}" style="min-height: 66px">'
				+ '<a class="thumb-sm pull-left m-r-sm" style="font-size:30px"> <span class="glyphicon glyphicon-random img-circle" aria-hidden="true"></span></a>'
				+ '<a class="clear"> <small class="pull-right"></small>  '
				+ '<strong class="block">{flowname}, {flowcode} </strong> '
				+ '<small>备注：{remark} </small></a>'
				+ '</li>';
		 		var html = '';
	 			if(store.getCount()>0){
			 		for (var i = 0; i < store.getCount(); i++) {
						var r=store.getAt(i);
						html += htmltpl.replaceAll("{remark}",r.get('REMARK')).replaceAll("{flowname}",r.get('FLOWNAME')).replaceAll("{flowcode}",r.get('FLOWCODE')).replaceAll("{xmlid}",r.get('XMLID'));
					};
				}else{
					html = '<span class = "empty">无流程数据</span>';
				}
				return html;				
			};
	 		var html = getFlowHtml(ds_teamFlow);
			$('#teamflowinfo').empty();
			var $append = $("#teamflowinfo").append(html);
			$append.find(".list-group-item").click( function() {
				$("#teamflowinfo .list-group-item").removeClass("active");
				$(this).addClass("active");
			});

		}
	 	buildMetaBaseInfo();
	 	// buildTeamRoleList();
	 	buildTeamUserList();
	 	buildTeamUserInfo();
	 	buildDbList();
	 	buildDbInfo();
	 	TeamPerMission.init({teamcode:objname,containerId:'metaTeamPerssionInfo'});
	 	// buildTabList();
	 	buildAPITree();
	 	buildTeamFlow();
	 	//团队信息编辑
		$("#editObjInfo").click(function(){
          	metasoft.editMetaObjBaseInfo({objtype:objtype,objid:objXMLID,storeAtMetaObj:'n',aftSave:buildMetaBaseInfo});
    	});
		$("#saveMetaPerssionInfo").click(function(){
    		if(!confirm("是否确认保存变更后的权限信息?")) return;
    		teamperssionstore.select("select * from metateampermission where 1=2");
    		$(".ai-treegrid-body-check:checked","#metaTeamPerssionInfo").each(function(){
		 		var _dbname = $(this).attr("DBNAME");
		 		var _ruleCode = $(this).attr("RULECODE");
		 		var _strutsKeyValue = _dbname+","+_ruleCode;
		 		var teamperssionRecord = teamperssionstore.getNewRecord();
		 		var dbStructRecord = dbStrutStore.getRecordByKey(_strutsKeyValue);
		 		for(var i = 0 ;i <dbStrutStore.fields.length;i++){
		 			teamperssionRecord.set(dbStrutStore.fields[i].name,dbStructRecord.get(dbStrutStore.fields[i].name));
	 			}
		 		teamperssionRecord.set("TEAM_CODE",objname);	
		 		var tempFuncId="";
		 		$(this).parent().parent().find("input:checkbox[name='FUNC_ID']:checked").each(function(i){
	 				if(0==i){
	 					tempFuncId = $(this).val();
	 				}else{
	 					tempFuncId += (","+$(this).val());
	 				}
		 		});
		 		teamperssionRecord.set("FUNC_ID",tempFuncId);
		 		
		 		var tempGroupCode="";
		 		$(this).parent().parent().find("input:checkbox[name='OWNER_GROUPCODE']:checked").each(function(i){
	 				if(0==i){
	 					tempGroupCode = $(this).val();
	 				}else{
	 					tempGroupCode += (","+$(this).val());
	 				}
		 		});
		 		teamperssionRecord.set("OWNER_GROUPCODE",tempGroupCode);
		 		teamperssionstore.add(teamperssionRecord);
		    });	
		 //直接删除
		ai.executeSQL("delete from metateampermission where team_code='"+objname+"'");
		teamperssionstore.cache.update=[];
		var rs = teamperssionstore.commit(true);
	    var rsJson = $.parseJSON(rs);
	    alert(rsJson.msg);
	});

    $("#resetTeamPermission").click(function(){
    	 TeamPerMission.reset();
    });
});
</script>
</head>
<body class="">
	<div class="container-fluid">
		<div class="row" id="teamInfo">
			<div class="col-sm-3" style="padding-left: 1px; padding-right: 1px">
				<h5> 租户基本信息<small id='tip'> </small> </h5>
				<section class="panel panel-info portlet-item" style="opacity: 1; z-index: 0;">
					<header class="panel-heading"> 详细信息 </header>
					<div class="panel-body "
						style="width: 100%; height: auto; padding: 0px" id="teambaseinfo">

					</div>
					<footer class="panel-footer"  > <a href="#" id="editObjInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>编辑</a>  </footer>
				</section>
			</div>
			<div class="col-sm-9">
				<h5><span id="funaction">租户分项详细信息</span></h5>
				<section class="panel panel-info">
					<header class="panel-heading">
						<span class="hidden-sm"> &nbsp; </span> <span id="taskname"
							style="float: left">详细信息</span>
						<ul class="nav nav-tabs pull-right">
							<li class="active"><a href="#tab0" data-toggle="tab"> <i class="fa fa-comments text-muted"> </i> 租户成员信息 </a></li>
							<li class=""><a href="#tab1" data-toggle="tab"> <i class="fa fa-comments text-muted"> </i> 租户数据库信息 </a></li>
							<li class=""><a href="#tab2" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 租户权限信息 </a></li>
							<li class="" style="display:none"><a href="#tab3" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 表授权信息 </a></li>
							<li class=""><a href="#tab4" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> API授权信息 </a></li>
							<li class=""><a href="#tab5" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 租户流程信息 </a></li>
						</ul>
					</header>
				</selection>
				<div class="panel-body">
					<div class="tab-content">
						<div class="tab-pane active" id="tab0">
							<div class="row">
							  <!-- <div class="col-md-3">
							  	<div class="panel panel-default">
							  			<div class="panel-heading"> <span class="font-thin m-l-md m-t">团队角色</span> </div>
							  	       <div class="panel-body" >
							  	       	    <div class="list-group no-radius no-border no-bg m-t-n-xxs m-b-none auto" id="teamrolelist">
							  	       	  </div>
							  	       	</div>
							  	      <div class="panel-footer no-border">
													<a id="addTeamRole" class="btn btn-sm btn-primary"> <i class="fa fa-css3"> </i> 创建 </a> <a id="delTeamRole" class="btn btn-sm btn-danger "> <i class="fa fa-times"> </i> 删除
													</a> <a id="editTeamRole" class="btn btn-sm btn-primary"> <i class="fa fa-css3"> </i> 修改 </a>
									  </div>
								</div>
							  </div> -->
							  <div class="col-md-12">
								<div class='toolbar'>
									<button id="selectteamuser" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>选择添加人员</button>
									<button id="deleteteamuser" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>删除</button>
									<button id="editteamuser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>修改</button>
								</div>
								<div class="panel-body" id="teamuserinfo"></div>
							</div>
						</div>
						</div>
						<div class="tab-pane" id="tab1">
								<div class='toolbar'>
									 
									<button id="selectDbInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>选择库</button>
									<button id="deleteDbInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>删除库权限</button>
									<!-- <button id="userDbInfo" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>数据库用户权限</button> -->
								</div>
								<div class="panel-body" id="transDbInfo"></div>
								<div class='toolbar'>
									<!-- <button id="addUser" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>增加用户</button>
									<button id="deleteUser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>删除用户</button> -->
									<!-- <button id="syncUser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>指定运行账号</button> -->
								</div>
								<div class="panel-body col-sm-6" id="userInfo" style="display:none">
									<section class="panel panel-info">
										<header class="panel-heading">
											<span class="hidden-sm"> &nbsp; </span><span id="taskname" style="float: left">数据库用户信息:</span>
										</header>
										<fieldset> 
											<table class="table">
												<tbody >
													<tr><th class="strong w-80px">用户名</th><td>
														<input type='text' id='user-username' style="width:220px;"/>
													</td></tr>
													<tr><th class="strong w-80px">密码</th><td>
														<input type='text' id='user-password' style="width:220px;"/>
													</td></tr>
													<tr><th class="strong w-80px">URL</th><td>
														<input type='text' id='user-url' style="width:220px;"/>
													</td></tr>
												</tbody>
											</table>
										</fieldset>
										<footer class="panel-footer"  > <a href="#" id="editUserInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>确认修改</a>  </footer>
									</section>
								</div>
						</div>
						<div class="tab-pane" id="tab2">
								<div class='toolbar'>
									<button id="resetTeamPermission" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>重置</button>
									<button id="saveMetaPerssionInfo" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>保存</button>
								</div>
								<div class="panel-body" id="metaTeamPerssionInfo"></div>
						</div>	
						<div class="tab-pane" id="tab3">
								<div class='toolbar'>
									<button id="selectTab" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>添加表</button>
									<button id="deleteTab" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>删除表权限</button>
								</div>
								<div class="panel-body" id="tabInfo"></div>
						</div>
						<div class="tab-pane" id="tab4">
							<section class="panel panel-default">
								<div class='toolbar'>
									<button id="saveAPI" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>保存</button>
								</div>
								<div class="panel-body slim-scroll"><ul id="APITree" class="ztree"></ul></div>
							</section>
						</div>
						<div class="tab-pane" id="tab5">
							<div class="col-md-12">
								<div class='toolbar'>
									<button id="addteamflow" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>选择添加流程</button>
									<button id="delteamflow" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>删除</button>
								</div>
								<div class="panel-body" id="teamflowinfo"></div>
							</div>
						</div>
					</div>	
				</div>		
			</div>	

		<div>
	</div>
	<div id="staffModal" class="modal fade">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title">人员信息</h4>
				</div>
				<div class="modal-body" id="staffForm"></div>
				<div class="modal-footer">
					<button id="dialog-cancel"type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button id="dialog-ok" type="button" class="btn btn-primary">确认</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->	
	<div id="dbModal" class="modal fade">
		<div class="modal-dialog" style="z-index: 10000;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close db-dialog-cancel">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title">数据库信息</h4>
				</div>
				<div class="modal-body" id="dbForm"></div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default db-dialog-cancel">取消</button>
					<button id="db-dialog-ok" type="button" class="btn btn-primary">确认</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
</body>
